package com.ymttest.business.service;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import com.ymatou.iapi.productmanager.parameter.ProdTplBean;
import com.ymt.core.tool.Logger;
import com.ymttest.database.model.SpuProperty;
import com.ymttest.database.model.YmtProductDescExtra;
import com.ymttest.database.mongo.ProductDescExtraWapper;
import com.ymttest.database.mongo.ProductDetailModelWapper;
import com.ymttest.database.mongo.YmtMongoDriverFactroy;
import com.ymttest.database.mongo.jproduct.ProductDescExtraNewWapper;
import com.ymttest.database.mongo.jproduct.ProductsWapper;
import com.ymttest.database.sqlwapper.SpuPropertyWapper;
import com.ymttest.database.sqlwapper.YmtProductCategoryWapper;
import com.ymttest.database.sqlwapper.YmtProductDescExtraWapper;
import com.ymttest.database.sqlwapper.YmtProductDescMapWapper;
import com.ymttest.database.sqlwapper.YmtProductPropertyWapper;
import com.ymttest.database.sqlwapper.YmtProductsIWapper;
import com.ymttest.utils.MapUtil;

public class SellerProductCallServiceV2 {
	private static SimpleDateFormat sdf = new SimpleDateFormat(
			"yyyy-MM-dd'T'HH:mm:ss");
	private static SimpleDateFormat sdfForName = new SimpleDateFormat(
			"MM-dd HH:mm:ss");

	public static Map<String, Object> getThirdCategoryAndPropertyValue()
			throws Exception {
		Map<String, Object> map = new HashMap<>();
		map.put("ThirdCategory", 1122);

		JSONObject property1 = new JSONObject();
		JSONArray PropertyValue1 = new JSONArray(Arrays.asList("莱卡"));
		property1.put("propertyId", 71);
		property1.put("propertyValues", PropertyValue1);

		JSONObject property2 = new JSONObject();
		JSONArray PropertyValue2 = new JSONArray(Arrays.asList("120mL"));
		property2.put("propertyId", 60);
		property2.put("propertyValues", PropertyValue2);

		map.put("PropertyList",
				new JSONArray(Arrays.asList(property1, property2)));

		return map;
	}
	/***
	 * 商品属性值检查
	 * 
	 * 
	 * @param productId
	 * @param tgtPropertyArray - [{"PropertyValue":["莱卡"],"PropertyId":71},{"PropertyValue":["青少年"],"PropertyId":9}]
	 * @throws Exception
	 */
	public static void checkProdProperty(String productId,
			JSONArray tgtPropertyArray) throws Exception {
		SpuPropertyWapper spuPropertyWapper = new SpuPropertyWapper();
		//check Sql
		List<Map<String, Object>> retsInSql = new YmtProductPropertyWapper()
				.selectByProdId(productId);
		Logger.verifyEquals(tgtPropertyArray.length(), retsInSql.size(),
				"sql 属性值记录比较");

		for (int i = 0; i < tgtPropertyArray.length(); i++) {
			String sPropertyId = tgtPropertyArray.getJSONObject(i).getString(
					"propertyId");
			JSONArray propertyValue = tgtPropertyArray.getJSONObject(i)
					.getJSONArray("propertyValues");
			List<String> propertyValueList = new ArrayList<>();
			for (int j = 0; j < propertyValue.length(); j++) {
				propertyValueList.add(propertyValue.getString(j));
			}

			Map<String, Object> retInSql = retsInSql
					.stream()
					.filter(ele -> ele.get("PropertyId").toString()
							.equals(sPropertyId)).findAny().orElse(null);

			if (retInSql == null) {
				Logger.verifyEquals(false, true, "Ymt_ProductProperty product:"
						+ productId + ",propertyid:" + sPropertyId + " 不存在");
			} else {
				JSONArray actValInSql = new JSONArray(Arrays.asList(retInSql
						.get("Value").toString().split(",")));
				AssertService.checkArray(actValInSql, propertyValue,
						"Ymt_ProductProperty value值检查");
			}
		}

		if (YmtMongoDriverFactroy.isNewMongoCheck()) {
			ProductDescExtraWapper productDescExtraWapper = new ProductDescExtraWapper();
			Logger.verifyEquals(1,
					productDescExtraWapper.getCountByProductId(productId),
					"ProductDescExtra 记录应该只有一条");
			Map<String, Object> mapInMgo = productDescExtraWapper
					.getByProductId(productId);
			if (tgtPropertyArray.length() == 0) {
				Logger.verifyIsNull(mapInMgo.get("PropertyList"), "属性值应该不存在");
			} else {
				JSONArray propertyListArray = new JSONArray(mapInMgo.get(
						"PropertyList").toString());

				JSONArray tgtArray = new JSONArray();
				for (int i = 0; i < tgtPropertyArray.length(); i++) {
					int sPropertyId = tgtPropertyArray.getJSONObject(i).getInt(
							"PropertyId");
					String sPropertyName = spuPropertyWapper.selectSpuPropertById(
							sPropertyId).getName();

					JSONArray propertyValue = tgtPropertyArray.getJSONObject(i)
							.getJSONArray("PropertyValue");
					List<String> propertyValueList = new ArrayList<>();
					for (int j = 0; j < propertyValue.length(); j++) {
						propertyValueList
								.add(propertyValue.getString(j).trim());
					}

					JSONObject temp = new JSONObject();
					temp.put("Key", sPropertyName);
					String tmpVal = "";
					for (int k = 0; k < propertyValueList.size(); k++) {
						tmpVal = tmpVal + "," + propertyValueList.get(k);
					}
					if (tmpVal.startsWith(",")) {
						tmpVal = tmpVal.substring(1, tmpVal.length());
					}

					//temp.put("Value", propertyValueList.toString().replace("[", "").replace("]", "").trim());
					temp.put("Value", tmpVal);

					tgtArray.put(temp);
				}

				AssertService.checkArray(propertyListArray, tgtArray);
			}
		}

		if (YmtMongoDriverFactroy.isNewJavaMgoCheck()) {
			ProductDescExtraNewWapper productDescExtraWapper = new ProductDescExtraNewWapper();
			Logger.verifyEquals(1,
					productDescExtraWapper.getCountByProductId(productId),
					"ProductDescExtraNewWapper 记录应该只有一条");
			Map<String, Object> mapInMgo = productDescExtraWapper
					.getByProductId(productId);
			if (tgtPropertyArray.length() == 0) {
				Logger.verifyEquals(0, new JSONArray(mapInMgo.get("props")
						.toString()).length(), "属性值应该不存在");
			} else {
				JSONArray propertyListArray = new JSONArray(mapInMgo.get(
						"props").toString());

				JSONArray tgtArray = new JSONArray();
				for (int i = 0; i < tgtPropertyArray.length(); i++) {
					int sPropertyId = tgtPropertyArray.getJSONObject(i).getInt(
							"propertyId");
					String sPropertyName = spuPropertyWapper.selectSpuPropertById(
							sPropertyId).getName();

					JSONArray propertyValue = tgtPropertyArray.getJSONObject(i)
							.getJSONArray("propertyValues");
					List<String> propertyValueList = new ArrayList<>();
					for (int j = 0; j < propertyValue.length(); j++) {
						propertyValueList.add(propertyValue.getString(j));
					}

					JSONObject temp = new JSONObject();
					temp.put("key", sPropertyName);
					String tmpVal = "";
					for (int k = 0; k < propertyValueList.size(); k++) {
						tmpVal = tmpVal + "," + propertyValueList.get(k);
					}
					if (tmpVal.startsWith(",")) {
						tmpVal = tmpVal.substring(1, tmpVal.length());
					}

					//temp.put("Value", propertyValueList.toString().replace("[", "").replace("]", "").trim());
					temp.put("value", tmpVal);

					tgtArray.put(temp);
				}

				AssertService.checkArray(propertyListArray, tgtArray);
			}

		}

	}
	public static void checkTemplateWithProd(String productId,
			List<ProdTplBean> prodTplBeanList) throws Exception {
		boolean isHasProd = (productId != null && !productId.equals(""));

		//check Sql template
		YmtProductDescExtraWapper ymtProductDescExtraWapper = new YmtProductDescExtraWapper();
		prodTplBeanList.forEach(ele -> {
			try {
				Logger.comment("YmtProductDescExtra check");
				YmtProductDescExtra datainSql = ymtProductDescExtraWapper
						.selectByTemplateId(ele.getTemplateId());
				Map<String, Object> mapInSql = MapUtil.pojoToMap(datainSql);

				if (mapInSql.get("picUrls") == null
						|| mapInSql.get("picUrls").toString().equals("")) {
					Logger.verifyEquals(0, ele.getPicUrls().size(),
							"Template 图片应该不存在");
				} else {
					List<String> tmpPicInSql = Arrays.asList(mapInSql
							.get("picUrls").toString().split(","));
					AssertService.checkArray(tmpPicInSql, ele.getPicUrls());
				}

				Map<String, Object> requestMap = MapUtil.hashMap();
				requestMap.put("ID", ele.getTemplateId());
				requestMap.put("sellerId", ele.getTemplateSellerId());
				requestMap.put("templateName", ele.getTemplateName());
				requestMap.put("description", ele.getTemplateDesc());
				requestMap.put("templateType", ele.getTemplateType());
				AssertService.assertResultEqual(requestMap, mapInSql);

			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		});

		if (isHasProd) {
			int thirdCategoryId = new YmtProductsIWapper()
					.selectProductByProductId(productId).get(0)
					.getiThirdCategoryId();
			@SuppressWarnings("unchecked")
			Map<String, Object> ret = new YmtProductCategoryWapper()
					.getProductCategoryByCategoryId(thirdCategoryId).get(0);

			String measurePicStr = ret.get("MeasurePic") != null ? ret.get(
					"MeasurePic").toString() : "";

			/*	ProdTplBean prodTplBeanTmp = prodTplBeanList.stream().filter(ele->ele.getTemplateType()==1).findFirst().orElse(null);
				if (prodTplBeanTmp!=null){
					List<String> picUrls = prodTplBeanTmp.getPicUrls();
					//if (!measurePicStr.equals("")){picUrls.add(measurePicStr);}
				}*/

			//1 check Sql product template info 
			List<Map<String, Object>> retMaps = new YmtProductDescMapWapper()
					.selectByProdId(productId);
			Logger.verifyEquals(1, retMaps.size(), "YmtProductDesc 记录应该只有一条");
			Map<String, Object> retMap = retMaps.get(0);
			prodTplBeanList.forEach(ele -> {
				Logger.comment("YmtProductDescMapW check");
				if (ele.getTemplateId() != 0) {
					switch (ele.getTemplateType()) {
						case 1 :
							Logger.verifyEquals(
									ele.getTemplateId(),
									Integer.parseInt(retMap.get(
											"SizeTemplateId").toString()),
									"YmtProductDescMapWapper SizeTemplateId");
							break;
						case 2 :
							Logger.verifyEquals(ele.getTemplateId(), Integer
									.parseInt(retMap.get("BuyerNoticeId")
											.toString()),
									"YmtProductDescMapWapper BuyerNoticeId");
							break;
						case 3 :
							Logger.verifyEquals(
									ele.getTemplateId(),
									Integer.parseInt(retMap.get(
											"SellerServiceId").toString()),
									"YmtProductDescMapWapper SellerServiceId");
							break;
						default :
							Logger.verifyEquals(
									false,
									true,
									"模板类型  应该在1,2,3之中。实际为:"
											+ ele.getTemplateType());
							break;
					}

				}
			});

			//check new Mongo product template info 
			if (YmtMongoDriverFactroy.isNewMongoCheck()) {
				//2 productDescExtra
				ProductDescExtraWapper productDescExtraWapper = new ProductDescExtraWapper();
				Logger.verifyEquals(1,
						productDescExtraWapper.getCountByProductId(productId),
						"ProductDescExtra 记录应该只有一条");
				Map<String, Object> mapInMgo = productDescExtraWapper
						.getByProductId(productId);

				prodTplBeanList.forEach(ele -> {
					try {
						if (ele.getTemplateId() != 0) {
							if (ele.getTemplateType() == 1) {
								JSONArray jsonArray = new JSONArray(ele
										.getPicUrls());
								if (!measurePicStr.equals("")) {
									jsonArray.put(measurePicStr);
								}
								AssertService.checkArray(
										jsonArray,
										new JSONArray(mapInMgo.get(
												"SizePicList").toString()));
							}

							if (ele.getTemplateType() == 2) {
								Logger.verifyEquals(ele.getTemplateDesc(),
										mapInMgo.get("NoticeText"),
										"ProductDescExtra noticeText");
								AssertService.checkArray(
										new JSONArray(ele.getPicUrls()),
										new JSONArray(mapInMgo.get(
												"NoticePicList").toString()));
							}

							if (ele.getTemplateType() == 3) {
								Logger.verifyEquals(ele.getTemplateDesc(),
										mapInMgo.get("SellerIntroText"),
										"ProductDescExtra SellerIntroText");
								AssertService.checkArray(
										new JSONArray(ele.getPicUrls()),
										new JSONArray(mapInMgo.get(
												"SellerIntroPicList")
												.toString()));
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				});

				//1 product detail 
				JSONArray sizePicsInMgo = new JSONArray(
						new ProductDetailModelWapper().getProductId(productId)
								.get("SizePicList").toString());
				ProdTplBean prodTplBean = prodTplBeanList.stream()
						.filter(ele -> ele.getTemplateType() == 1).findFirst()
						.orElse(null);

				if (prodTplBean == null) {
					//没有size list
					Logger.verifyEquals(0, sizePicsInMgo.length(),
							"应该没有size pic list");
					Logger.verifyEquals(0,
							new JSONArray(mapInMgo.get("SizePicList")
									.toString()).length(), "应该没有size pic list");

				} else {
					JSONArray jsonArray = new JSONArray(
							prodTplBean.getPicUrls());
					if (!measurePicStr.equals("")) {
						jsonArray.put(measurePicStr);
					}
					AssertService.checkArray(sizePicsInMgo, jsonArray,
							"ProductDetailMap-Size pic 比较");
				}
			}

			//check java new Mongo
			if (YmtMongoDriverFactroy.isNewJavaMgoCheck()) {
				//2 productDescExtra
				ProductDescExtraNewWapper productDescExtraWapper = new ProductDescExtraNewWapper();
				Logger.verifyEquals(1,
						productDescExtraWapper.getCountByProductId(productId),
						"ProductDescExtraNew 记录应该只有一条");
				Map<String, Object> mapInMgo = productDescExtraWapper
						.getByProductId(productId);

				prodTplBeanList.forEach(ele -> {
					try {
						if (ele.getTemplateId() != 0) {
							if (ele.getTemplateType() == 1) {
								JSONArray jsonArray = new JSONArray(ele
										.getPicUrls());
								if (!measurePicStr.equals("")) {
									jsonArray.put(measurePicStr);
								}
								AssertService.checkArray(jsonArray,
										new JSONArray(mapInMgo.get("sizepics")
												.toString()));
							}

							if (ele.getTemplateType() == 2) {
								Logger.verifyEquals(ele.getTemplateDesc(),
										mapInMgo.get("notice"),
										"ProductDescExtraNew noticeText");
								AssertService.checkArray(
										new JSONArray(ele.getPicUrls()),
										new JSONArray(mapInMgo.get("notipics")
												.toString()));
							}

							if (ele.getTemplateType() == 3) {
								Logger.verifyEquals(ele.getTemplateDesc(),
										mapInMgo.get("intro"),
										"ProductDescExtraNew SellerIntroText");
								AssertService.checkArray(
										new JSONArray(ele.getPicUrls()),
										new JSONArray(mapInMgo.get("intropics")
												.toString()));
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				});

				//1 product detail 
				ProdTplBean prodTplBean = prodTplBeanList.stream()
						.filter(ele -> ele.getTemplateType() == 1).findFirst()
						.orElse(null);
				if (prodTplBean == null) {
					//没有size   list
					Logger.verifyIsNull(
							new ProductsWapper().getByProductId(productId).get(
									"sizepics"), "应该没有size pic list");
					Logger.verifyIsNull(mapInMgo.get("sizepics"),
							"应该没有size pic list");
				} else {
					JSONArray jsonArray = new JSONArray(
							prodTplBean.getPicUrls());
					if (!measurePicStr.equals("")) {
						jsonArray.put(measurePicStr);
					}
					JSONArray sizePicsInMgo = new JSONArray(
							new ProductsWapper().getByProductId(productId)
									.get("sizepics").toString());
					AssertService.checkArray(sizePicsInMgo, jsonArray,
							"Product-Size pic 比较");
				}
			}

		}

	}

	/***
	 * 
	 * @param propertyList
	 * @param thirdCategoryId
	 * @param PropertyListHasVal
	 * @throws Exception
	 */
	public static void checkPropertyList(JSONArray propertyList,
			int thirdCategoryId, JSONArray PropertyListHasVal) throws Exception {
		List<SpuProperty> spuPropertyList = new SpuPropertyWapper()
				.selectByThirdcategoryidId(thirdCategoryId);
		Logger.verifyEquals(spuPropertyList.size(), propertyList.length(),
				"商品信息 返回校验 PropertyList record");

		for (int i = 0; i < propertyList.length(); i++) {
			JSONObject propertyJson = propertyList.getJSONObject(i);
			Integer PropertyId = propertyJson.getInt("PropertyId");
			SpuProperty spuProperty = spuPropertyList.stream()
					.filter(ele -> ele.getPropertyId().equals(PropertyId))
					.findFirst().orElse(null);

			Logger.verifyNotNull(spuProperty, "spuProperty propertyid:"
					+ PropertyId + " should be exists.");

			Map<String, Object> tgtMap = new HashMap<>();
			tgtMap.put("PropertyName", spuProperty.getName());
			tgtMap.put("PropertyValueType", spuProperty.getStyles());
			tgtMap.put("IsMultiple", spuProperty.getMultiSelect());

			//to do values check 
			propertyJson.remove("Values");
			AssertService.assertResultEqual(tgtMap,
					MapUtil.jsonToMap(propertyJson), "PropertyList id:"
							+ PropertyId + "check ");

			//property value check if has 
			JSONArray propertys = PropertyListHasVal;
			if (PropertyListHasVal != null && PropertyListHasVal.length() > 0) {
				boolean isHasVal = false;
				for (int j = 0; j < propertys.length(); j++) {
					if (propertys.getJSONObject(j).getInt("propertyId") == PropertyId) {
						AssertService.checkArray((propertys.getJSONObject(j)
								.getJSONArray("propertyValues")), propertyJson
								.getJSONArray("InputValues"));
						isHasVal = true;
						break;
					}
				}

				if (!isHasVal) {
					Logger.verifyEquals(0,
							propertyJson.getJSONArray("InputValues").length(),
							"InputValues should be empty");
				}
			}
		}

	}

	
	public static void main(String[] args) throws Exception {
		//CatalogLevelBean a = getProductCategroyByThirdCategoryId(1003);
		//int cc = 1;
		//int bb = cc;
	}
}
